var express = require('express');
var router = express.Router();

const jwt = require('jsonwebtoken');
let secret = 'houduan'

const infoSchema = require('../module/userinfo');
const loginSchema = require('../module/login');
const addressSchema = require('../module/address');


//获取账号密码,如果账号重复则验证密码，如果没有，则生成token
router.post('/login', function (req, res, next) {
    let { username, password } = req.body
    console.log(req.body)
    let token = jwt.sign({ username }, secret, {
        expiresIn: 60 * 60 * 5
    })
    loginSchema.find({ username }, (err, doc) => {
        if (doc.length) {
            loginSchema.find({ username, password }, (err, doc) => {

                if (err) throw err;
                if (doc.length) {
                    res.json({
                        status: 0,
                        msg: "登入成功",
                        token: token
                    })
                } else {
                    res.json({
                        status:1,
                        msg: '账号或密码错误'
                    })
                }
            })
        } else {
            infoSchema.create({ photo: '', year: "", month: "", day: "", username, sex: "未知", city: "三沙市",phone:username })
            // addressSchema.create({id:username,result:[],index:0})
            loginSchema.create({ username, password }, (err, doc) => {
                if (err) throw err
                res.json({
                    status: 0,
                    msg: "注册并登入成功",
                    token: token
                })
            })
        }
    })
});

router.post('/token', function (req, res, next) {
    let { token } = req.body
    try {
        let data = jwt.verify(token, secret)
        res.json({
            msg: 0,
            msg:"token未过期，可正常使用"
        })
    } catch (error) {
        res.json({
            status:4,
            msg: "token过期，请重新登入"
        })
    }

});



module.exports = router;